package cn.virens.common.mybatis.service.spring;

import cn.virens.common.mybatis.entity.BaseModel;
import cn.virens.common.mybatis.mapper.AbstrMapper;
import cn.virens.common.mybatis.mapper.example.Example;
import cn.virens.common.util.exception.APIException;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * 通用service实现类
 *
 * @param <M> DO层接口类型
 * @param <T> 实体类型
 * @author virens
 */
public abstract class BaseWriteServiceImpl<M extends AbstrMapper<T>, T extends BaseModel> extends BaseReadServiceImpl<M, T> implements BaseWriteService<T> {

    public BaseWriteServiceImpl(Class<T> clazz) {
        super(clazz);
    }

    @Override
    @Transactional(readOnly = false)
    public T insert(T record) throws APIException {
        if (mBaseMapper.insertSelective(record) > 0) {
            return record;
        } else {
            return null;
        }
    }

    @Override
    @Transactional(readOnly = false)
    public T update(T record) throws APIException {
        if (mBaseMapper.updateByPrimaryKeySelective(record) > 0) {
            return record;
        } else {
            return null;
        }
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(Serializable id) throws APIException {
        return mBaseMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询指定条件下的条数
     *
     * @param example 条件构造
     * @return 执行结果
     * @throws APIException 一般异常
     */
    protected long countByExample(Example example) throws APIException {
        return mBaseMapper.selectCountByExample(example);
    }

    /**
     * 删除数据，如果成功返回对应操作数量
     *
     * @param example 条件构造
     * @return 执行结果
     * @throws APIException 一般异常
     */
    protected int deleteByExample(Example example) throws APIException {
        return mBaseMapper.deleteByExample(example);
    }

    /**
     * 更新数据，如果成功返回对应实体
     *
     * @param record  实体对象
     * @param example 条件构造
     * @return 执行结果
     * @throws APIException 一般异常
     */
    protected T updateByExample(T record, Example example) throws APIException {
        if (mBaseMapper.updateByExampleSelective(record, example) > 0) {
            return record;
        } else {
            return null;
        }
    }
}
